const axios = require('axios');
const jwt = require('jsonwebtoken');
import { getUserByOpenid, WeChatCreatUser } from '../models/userModel';


const appid = 'wx132d5f2f94f56932';
const appsecret = '82391dfee87cd13014960679c919aa85';

// 微信登录逻辑
export const wxLogin = async (req: any, res: any) => {
    const { code, phone } = req.body;
    // 检查code
    if (!code) {
        return res.status(400).json({ message: 'Code is required' });
    }
    try {
        // 获取openid和session_key
        const response = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
            params: {
                appid: appid,
                secret: appsecret,
                js_code: code,
                grant_type: 'authorization_code'
            }
        });
        const { openid, session_key } = response.data;
        // 检查openid是否获取成功
        if (!openid) {
            return res.status(400).json({ message: 'Failed to get openid from WeChat' });
        }
        // 查询用户是否存在
        const user = await getUserByOpenid(openid);
        // 如果用户不存在，注册新用户并返回token
        if (!user) {
            console.log('没有查询到用户，注册新用户');
            // 创建新用户
            const newUser = await WeChatCreatUser(openid, session_key, new Date());
            // 生成JWT token
            const token = jwt.sign({ openid: newUser.openid }, process.env.JWT_SECRET as string, { expiresIn: '144h' });
            return res.json({
                status: 200,
                message: "登录成功",
                token: 'Bearer ' + token,
            });
        }
        // 如果用户已注册，返回token
        const token = jwt.sign({ openid: user.openid, id: user.id, phone: user.phone }, process.env.JWT_SECRET as string, { expiresIn: '144h' });
        return res.json({
            status: 200,
            message: "登录成功",
            token: 'Bearer ' + token,
        });
    } catch (error) {
        console.error('WeChat API request failed:', error);
        return res.status(500).json({ message: 'WeChat API request failed' });
    }
};